package com.yupi.moshu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yupi.moshu.common.BaseResponse;
import com.yupi.moshu.common.ErrorCode;
import com.yupi.moshu.common.ResultUtils;
import com.yupi.moshu.exception.BusinessException;
import com.yupi.moshu.mapper.TeamUserMapper;
import com.yupi.moshu.model.domain.Member;
import com.yupi.moshu.model.domain.Team;
import com.yupi.moshu.model.domain.TeamUser;
import com.yupi.moshu.model.domain.User;
import com.yupi.moshu.model.request.CreateTeamRequest;
import com.yupi.moshu.model.request.InviteRequest;
import com.yupi.moshu.model.request.SearchTeamRequest;
import com.yupi.moshu.model.request.KickRequest;
import com.yupi.moshu.model.request.ChangePowerRequest;
import com.yupi.moshu.model.request.DismissTeamRequest;
import com.yupi.moshu.model.request.MemberListRequest;
import com.yupi.moshu.model.request.Id2nameRequest;
import com.yupi.moshu.model.request.Email2userRequest;
import com.yupi.moshu.model.request.CheckPowerRequest;
import com.yupi.moshu.model.request.ViewAllTeamRequest;
import com.yupi.moshu.service.TeamService;
import com.yupi.moshu.service.TeamUserService;
import com.yupi.moshu.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 团队管理接口
 * @author 7
 */
@RestController
@RequestMapping("/team")
public class TeamController {
    @Resource
    private TeamService teamService;

    @Resource
    private UserService userService;

    @Resource
    private TeamUserService teamUserService;

    @Resource
    private TeamUserMapper teamUserMapper;

    @PostMapping(value = "/createTeam")
    public BaseResponse<Void> createTeam(@RequestBody CreateTeamRequest createTeamRequest) {
        Long userID = createTeamRequest.getUserID();
        String teamName = createTeamRequest.getTeamName();
        Integer isPrivate = createTeamRequest.getIsPrivate();

//        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
//        if ( teamService.count(teamQueryWrapper)>0) {
//            return ResultUtils.success("团队创建失败");
//        }

        Team team = new Team();
        team.setCreatorID(userID);
        team.setTeamName(teamName);
        team.setIsPrivate(isPrivate);
        teamService.save(team);

        TeamUser teamUser = new TeamUser();
        teamUser.setUserID(userID);
//        teamUser.setTeamID(teamService.count());     出错？   考虑解散团队  count！=id
        teamUser.setTeamID(team.getId());
        teamUser.setUserRole(2);
        teamUserService.save(teamUser);

        return ResultUtils.success("团队创建成功");
    }

    @PostMapping(value = "/inviteMember")
    public BaseResponse<Void> inviteMember(@RequestBody InviteRequest inviteRequest) {
        String email = inviteRequest.getEmail();
        Long teamID = inviteRequest.getTeamID();

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email", email);
        User user = userService.getOne(userQueryWrapper);

        QueryWrapper<TeamUser> teamUserQueryWrapper = new QueryWrapper<>();
        teamUserQueryWrapper.eq("userID", user.getId()).eq("teamID", teamID);
        long count = teamUserMapper.selectCount(teamUserQueryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该成员已加入团队，无需重复邀请");
        }

        TeamUser teamUser = new TeamUser();
        teamUser.setUserID(user.getId());
        teamUser.setTeamID(teamID);
        teamUser.setUserRole(0);
        teamUserService.save(teamUser);

        Integer memberCnt = teamService.getById(teamID).getMemberCnt();
        UpdateWrapper<Team> teamUpdateWrapper = new UpdateWrapper<>();
        teamUpdateWrapper.eq("id", teamID).set("memberCnt", memberCnt+1);
        teamService.update(teamUpdateWrapper);

        return ResultUtils.success("已邀请成员加入");
    }

    @PostMapping(value = "/viewAllTeam")
    public BaseResponse<List<Team>> viewAllTeam(@RequestBody ViewAllTeamRequest viewAllTeamRequest) {
        int role = viewAllTeamRequest.getRole();
        Long userID = viewAllTeamRequest.getUserID();
        if (userID == 0) {
            List<Team> teamList = teamService.list();
            return ResultUtils.success(teamList);
        } else if (role == -1) {
            QueryWrapper<TeamUser> teamUserQueryWrapper = new QueryWrapper<>();
            teamUserQueryWrapper.eq("userID", userID).eq("userRole", role);

            List<TeamUser> list = teamUserService.list(teamUserQueryWrapper);

            List<Team> retList = new ArrayList<>();
            for(TeamUser i : list) {
                Long teamID = i.getTeamID();

                QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
                teamQueryWrapper.eq("id", teamID);
                Team team = teamService.getOne(teamQueryWrapper);

                retList.add(team);
            }
            return ResultUtils.success(retList);
        } else {
            QueryWrapper<TeamUser> teamUserQueryWrapper = new QueryWrapper<>();
            teamUserQueryWrapper.eq("userID", userID).eq("userRole", role);

            List<TeamUser> list = teamUserService.list(teamUserQueryWrapper);

            List<Team> retList = new ArrayList<>();
            for(TeamUser i : list) {
                Long teamID = i.getTeamID();
                QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
                teamQueryWrapper.eq("id", teamID);
                Team team = teamService.getOne(teamQueryWrapper);

                retList.add(team);
            }
            return ResultUtils.success(retList);
        }
    }

    @PostMapping(value = "/searchTeam")
    public BaseResponse<List<Team>> searchTeam(@RequestBody SearchTeamRequest searchTeamRequest) {
        String teamName = searchTeamRequest.getTeamName();
        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
        teamQueryWrapper.like("teamName", teamName);
        List<Team> teamList = teamService.list(teamQueryWrapper);
        return ResultUtils.success(teamList);
    }

    @PostMapping(value = "/kickMember")
    public BaseResponse<Void> kickMember(@RequestBody KickRequest kickRequest) {
        Long userID = kickRequest.getUserID();
        Long teamID = kickRequest.getTeamID();


        QueryWrapper<TeamUser> teamUserQueryWrapper = new QueryWrapper<>();
        teamUserQueryWrapper.eq("userID", userID).eq("teamID", teamID);
        teamUserService.remove(teamUserQueryWrapper);

        Integer memberCnt = teamService.getById(teamID).getMemberCnt();
        UpdateWrapper<Team> teamUpdateWrapper = new UpdateWrapper<>();
        teamUpdateWrapper.eq("id", teamID).set("memberCnt", memberCnt-1);
        teamService.update(teamUpdateWrapper);

        return ResultUtils.success("已踢出成员");
    }

    @PostMapping(value = "/changePower")
    public BaseResponse<Void> changePower(@RequestBody ChangePowerRequest changePowerRequest) {
        Long teamID = changePowerRequest.getTeamID();
        Long userID = changePowerRequest.getUserID();
        int power = changePowerRequest.getPower();

//        System.out.println("--------------");
//        System.out.println(teamID);
//        System.out.println(userID);
//        System.out.println(teamID);

        UpdateWrapper<TeamUser> teamUserUpdateWrapper = new UpdateWrapper<>();
        teamUserUpdateWrapper.eq("userID", userID).eq("teamID", teamID);
        teamUserUpdateWrapper.set("userRole" , power);
        teamUserService.update(teamUserUpdateWrapper);

        return ResultUtils.success("已改变成员权限");
    }


    @PostMapping(value = "/dismissTeam")
    public BaseResponse<Void> dismissTeam(@RequestBody DismissTeamRequest dismissTeamRequest) {
        Long teamID = dismissTeamRequest.getTeamID();
        Long userID = dismissTeamRequest.getUserID();

        QueryWrapper<TeamUser> teamUserQueryWrapper = new QueryWrapper<>();
        teamUserQueryWrapper.eq("teamID", teamID);
        teamUserService.remove(teamUserQueryWrapper);

        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
        teamQueryWrapper.eq("id", teamID).eq("creatorID", userID);
        teamService.remove(teamQueryWrapper);

        return ResultUtils.success("解散团队成功");
    }

    @PostMapping(value = "/memberList")
    public BaseResponse<List<Member>> memberList(@RequestBody MemberListRequest memberListRequest) {
        Long teamID = memberListRequest.getTeamID();

        QueryWrapper<TeamUser> teamUserQueryWrapper = new QueryWrapper<>();
        teamUserQueryWrapper.eq("teamID", teamID);

        List<TeamUser> list = teamUserService.list(teamUserQueryWrapper);

        List<Member> memberList = new ArrayList<>();
        for(TeamUser i : list) {
            Long userID = i.getUserID();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("id", userID);
            User user = userService.getOne(userQueryWrapper);

            Member member = new Member();
            member.setUserID(userID);
            member.setNikeName(user.getNickName());
            member.setRealName(user.getRealName());
            member.setEmail(user.getEmail());
            member.setCity(user.getCity());
            member.setAvatarUrl(user.getAvatarUrl());
            member.setUserRole(i.getUserRole());

            memberList.add(member);
        }
        return ResultUtils.success(memberList);
    }

    @PostMapping(value = "/id2name")
    public BaseResponse<Void> id2name(@RequestBody Id2nameRequest id2nameRequest) {
        Long teamID = id2nameRequest.getTeamID();

        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
        teamQueryWrapper.eq("id", teamID);
        String ret = teamService.getOne(teamQueryWrapper).getTeamName();

        return ResultUtils.success(ret);
    }

    @PostMapping(value = "/email2user")
    public BaseResponse<User> email2user(@RequestBody Email2userRequest email2userRequest) {
        String email = email2userRequest.getEmail();

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email", email);
        User user = userService.getOne(userQueryWrapper);

        return ResultUtils.success(user);
    }

    @PostMapping(value = "/checkPower")
    public BaseResponse<Integer> checkPower(@RequestBody CheckPowerRequest checkPowerRequest) {
        Long userID = checkPowerRequest.getUserID();
        Long teamID = checkPowerRequest.getTeamID();


        QueryWrapper<TeamUser> teamUserQueryWrapper = new QueryWrapper<>();
        teamUserQueryWrapper.eq("userID", userID).eq("teamID",teamID);
        TeamUser teamuser = teamUserService.getOne(teamUserQueryWrapper);

        return ResultUtils.success(teamuser.getUserRole());
    }
}
